package com.dx.financehy.enums;

import java.util.*;

/**
 * <pre>
 * @描述：
 * @作者：CLD
 * @创建时间：2022-06-14 17:18
 * </pre>
 **/
public class EnumHelper<E extends IEnum<Integer, String>> {

    private final Class<E> enumType;

    public EnumHelper(Class<E> enumType) {
        this.enumType = enumType;
    }

    /**
     * 根据code转换枚举类型
     */
    public static <E extends IEnum<Integer, String>> E valueOf(Class<E> enumType, Object code) {
        E[] all = enumType.getEnumConstants();
        if (all == null || all.length == 0) {
            return null;
        }
        for (E e : all) {
            if (Objects.equals(code, e.getCode())) {
                return e;
            }
        }
        return null;
    }

    public static <E extends IEnum<Integer, String>> E valueOfDesc(Class<E> enumType, Object desc) {
        E[] all = enumType.getEnumConstants();
        if (all == null || all.length == 0) {
            return null;
        }
        for (E e : all) {
            if (Objects.equals(desc, e.getDesc())) {
                return e;
            }
        }
        return null;
    }

    /**
     * 获取枚举List列表
     */
    public static <E extends IEnum<Integer, String>> List<Map<Object, Object>> getEnumList(Class<E> enumType) {
        E[] all = enumType.getEnumConstants();
        if (all == null || all.length == 0) {
            return null;
        }
        List<Map<Object, Object>> list = new ArrayList<>();
        for (E e : all) {
            Map<Object, Object> map = new HashMap<>();
            map.put("code", e.getCode());
            map.put("desc", e.getDesc());
            list.add(map);
        }
        return list;
    }

    public E valueOf(Object code) {
        return valueOf(this.enumType, code);
    }
}
